﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Xml.Serialization;

namespace Wp7Tools.Services {
	public class XmlDataStorage : IXmlDataStorage {

		private object _sync = new object();

		public void Save(string file, object obj) {
			lock (_sync) {
				Type type = obj.GetType();
				XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
				xmlWriterSettings.Indent = true;
				using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
					using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(file, FileMode.Create)) {
						XmlSerializer serializer = new XmlSerializer(type);
						using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings)) {
							serializer.Serialize(xmlWriter, obj);
						}
					}
				}
			}
		}

		public T Load<T>(string file) {
			lock (_sync) {
				using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
					using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(file, FileMode.Open)) {
						XmlSerializer serializer = new XmlSerializer(typeof (T));
						T data = (T) serializer.Deserialize(stream);
						return data;
					}
				}
			}
		}

		public bool Exists(string file) {
			lock (_sync) {
				using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) {
					return myIsolatedStorage.FileExists(file);
				}
			}
		}
	}
}